<?php
namespace hema\device\engine;


/**
 * 大趋智能云打印机驱动模块
 * 测试机型号：P7
 */
class Daqu extends Basics
{
    /**
    * 打印订单接口
    * $dev = 设备参数,$content=打印模板
    */
    public function print($dev,$content)
    {
        $content = $this->make_templet($content);//转换打印模板
        if($dev['tpl'] ==0){
            $voice = '10';//新订单
        }else{
            $voice = '11'; //退款订单
        }
        $params = [
            "sn" => $dev['dev_id'],//打印机终端号
            "voice" => $voice, //语音内容
            "content" => $content,//打印内容
            "copies" => (int)$dev['prt_num']     //打印分数

        ];
        $result = json_decode($this->http_post_json('print','POST',$params,true),true);
        sleep(1);//延时1秒
        if($result['code'] != 0){
            $this->error = $result['message'];
            return false;
        }
        return $result;
    }
    
    /**
    * 授权绑定打印机
    */
    public function add($data)
    {
        $params = [
            [
                "sn" =>  $data['dev_id'],//打印机终端号
                "key"=> $data['dev_key'],//打印机终端密钥
                "name"=>$data['dev_name'],//自定义打印机名称(可填)
            ]
        ];
        $result = json_decode($this->http_post_json('addPrinter','POST',$params,true),true);
        if($result['code'] != 0){
            $this->error = $result['message'];
            return false;
        }
        if(isset($result['data']['fail'][0]['reason'])){
            $this->error = $result['data']['fail'][0]['reason'];
            return false;
        }
        return $result;
    }
    
    /**
    * 删除授权绑定的打印机
    */
    public function delete($dev_id)
    {
        $params = [$dev_id];
        $result = json_decode($this->http_post_json('delPrinter','POST',$params,true),true);
        if($result['code'] != 0){
            $this->error = $result['message'];
            return false;
        }
        if(isset($result['data']['fail'][0]['reason'])){
            $this->error = $result['data']['fail'][0]['reason'];
            return false;
        }
        return $result;
    }
    
    /**
    * 获取打印机状态接口 
    */
    public function status($dev_id)
    {
        $params['sn'] = $dev_id;
        $result = json_decode($this->http_post_json('getDeviceStatus','POST',$params,true),true);
        sleep(1);//延时1秒
        if($result['code'] != 0){
            return '未知';
        }
        if($result['data']['onlineStatus'] == 1){
            if($result['data']['workStatus'] == 0){
                return '正常';
            }
            return $result['data']['workStatusDesc'];
        }
        return '离线';
    }

    // 请求工具方法
    public function http_post_json($url, $method = 'GET', $postfields = null, $debug = false) 
    {
        $url = $this->config['api_url'] . '/openapi/' . $url;
        $headers = $this->getHeader($postfields); 
        $body = hema_json($postfields);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers); // 设置通用传参
        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $body);
                }
                break;
        }

        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false);// 从证书中检查SSL加密算法是否存在
        curl_setopt($ci, CURLOPT_URL, $url);
        $response = curl_exec($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        $request_header = curl_getinfo($ci, CURLINFO_HEADER_OUT);
        curl_close($ci);
        return $response;
    }
    
    // Header通用参数
    private function getHeader($data)
    {
        $body = hema_json($data);
        $timestamp = time();
        $uid = md5($timestamp);
        $sign = md5($uid . $this->config['app_key'] . $timestamp . $this->config['app_secret'] . $body);
        $header = array();
        $header[] = "Content-Type:application/json";
        $header[] = "appid:" . $this->config['app_key'];
        $header[] = "uid:" . $uid;
        $header[] = "stime:" . $timestamp;
        $header[] = "sign:" . $sign;
        return $header;
        
        
    }
    
    /**
     * 制作订单模板
     * $data 订单数据
     * 58mm的机器,一行打印16个汉字,32个字母;
     */
    private function make_templet($data)
    {
        /*
        <BR>              换行符
        <C></C>           居中
        <LEFT></LEFT>     左对齐
        <RIGHT></RIGHT>   右对齐
        <QR></QR>         二维码内容，字符个数范围：<=128个字节
        <BAR></BAR>       条形码，编码方式：CODE 128B字体，字符个数范围: n < 15
        <font# bolder="" height="" width=""></font#>   字体大小设置，bolder是否加粗[0 普通 1 加粗]  height倍高[取值1-8] width倍宽[取值1-8]
        */
        $content = '';
        foreach ($data as $item){
            $row_arr = explode(',',$item);
            $row = $row_arr[0];
            for($m=1;$m<sizeof($row_arr);$m++){
                //放大
                if($row_arr[$m] == '<B>'){
                    $row = "<font# bolder=1 height=2 width=2>" . $row . "</font#>";
                }
                //居中
                if($row_arr[$m] == '<C>'){
                    $row = "<C>" . $row . "</C>";
                }
            }
            $content .= $row . "<BR>";
        }
        $content .= "<BR><BR>";
        return $content;
    }
}
